<script setup>
    import roleApi from '@/api/admin/role.js'
    import permissionApi from '@/api/admin/permission.js'
    import hasBtnPermission from "@/utils/btnPermission.js";
    import {ref, reactive} from 'vue'
    import {
        Delete,
        Edit,
    } from '@element-plus/icons-vue'
    import {ElMessage, ElMessageBox} from 'element-plus'

    //表格数据
    const list = ref([])
    const total = ref(0)
    //分页信息和搜索条件
    const roleQuery = reactive({
        name: '',
        code: '',
        page: 1,
        limit: 10
    })

    /*function loadData() {
        roleApi.list(roleQuery).then(result => {
            list.value = result.data.list
            total.value = result.data.total
        })
    }*/
    const loadData = () => {
        roleApi.list(roleQuery).then(result => {
            list.value = result.data.records
            total.value = result.data.total
        })
    }

    loadData()

    const onSearch = () => {
        roleQuery.page = 1
        loadData()
    }

    //根据id删除
    const deleteById = (id) => {
        ElMessageBox.confirm(
            '您确认要删除么?',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                lockScroll: false //防止抖动
            }
        ).then(() => {
            roleApi.deleteById(id).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        })
    }

    const ids = ref([])
    const handleSelectionChange = (rows) => {
        //console.log('多选', rows)
        ids.value = rows.map(row => row.id)
        console.log(ids.value)
    }

    const deleteAll = () => {
        ElMessageBox.confirm(
            '您确认要删除么?',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                lockScroll: false //防止抖动
            }
        ).then(() => {
            roleApi.deleteAll(ids.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        })
    }


    //添加、编辑
    const dialogFormVisible = ref(false)
    const role = ref({})
    const title = ref()

    const showAddDialog = () => {
        dialogFormVisible.value = true
        title.value = '添加'
        role.value = {}
    }

    const showUpdateDialog = (id) => {
        dialogFormVisible.value = true
        title.value = '编辑'
        role.value = {}
        roleApi.selectById(id).then(result => {
            role.value = result.data
        })
    }

    const addOrUpdate = () => {
        if (role.value.id) {//编辑
            roleApi.update(role.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                    dialogFormVisible.value = false
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        } else {//添加
            roleApi.add(role.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                    dialogFormVisible.value = false
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        }
    }

    import {Plus} from '@element-plus/icons-vue'

    const handleAvatarSuccess = (result) => {
        role.value.image = result.data
    }

    import {useTokenStore} from '@/store/token.js'
    const tokenStore = useTokenStore()
    const headers = ref({
		//添加token
		Authorization: tokenStore.token
	})

    //权限分配的树形结构
    const dialogPermissionVisible = ref(false)
    const treeData = ref([])
    const treeRef = ref()
    const defaultProps = ref({
        children: 'children',
        label: 'name'
    })
    const showAssignedPermissionDialog = (row) => {
        role.value = row;
        dialogPermissionVisible.value = true;
        treeData.value = [];
        permissionApi.selectAssignedPermission(row.id).then((result) => {
            if (result.code === 0) {
                treeData.value = result.data.permissionVOList;
                let checkedLeafIdList = [];
                getCheckedLeafIdList(result.data.permissionVOList, result.data.assignedPermissionIdList, checkedLeafIdList);
                treeRef.value.setCheckedKeys(checkedLeafIdList);
            }
        });
    }

    const getCheckedLeafIdList = (permissionVOList, assignedPermissionIdList, checkedLeafIdList) => {
        permissionVOList.forEach(permissionVO => {
            assignedPermissionIdList.forEach(id => {
                //这个角色下面的权限，而且是没有孩子的叶子节点
                if (permissionVO.id==id && permissionVO.children.length == 0) {
                    checkedLeafIdList.push(id);
                } else if(permissionVO.id==id && permissionVO.children.length != 0) {
                    getCheckedLeafIdList(permissionVO.children, assignedPermissionIdList, checkedLeafIdList);
                }
            })
        });
    }

    const assignPermission = () => {
        let checkedNodes = treeRef.value.getCheckedNodes(false, true);
        console.log(checkedNodes);
        let permissionIds = checkedNodes.map((node) => node.id);
        permissionIds = permissionIds.join(',');
        permissionApi.assignPermission(role.value.id, permissionIds).then((result) => {
            if (result.code === 0) {
                ElMessage({message: result.msg, type: 'success',})
                dialogPermissionVisible.value = false;
            }
        });
    }
</script>

<template>
	<el-card class="">
		<template #header>
			<div class="header">
				<el-button type="primary" @click="showAddDialog" :disabled="!hasBtnPermission('role:add')">添加</el-button>
				<el-button type="primary" @click="deleteAll">批量删除</el-button>
			</div>
		</template>
		<el-form :inline="true">
			<el-form-item label="名字">
				<el-input v-model="roleQuery.name" placeholder="请输入名字" clearable/>
			</el-form-item>
			<el-form-item label="编码">
				<el-input v-model="roleQuery.code" placeholder="请输入编码" clearable/>
			</el-form-item>
			<el-form-item label="更新时间" :label-width="100">
				<el-date-picker
					v-model="roleQuery.beginUpdateTime"
					type="datetime"
					value-format="YYYY-MM-DD HH:mm:ss"
					placeholder="开始时间"
				/>
				<el-date-picker
					v-model="roleQuery.endUpdateTime"
					type="datetime"
					value-format="YYYY-MM-DD HH:mm:ss"
					placeholder="结束时间"
				/>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="onSearch">搜索</el-button>
			</el-form-item>
		</el-form>
		<el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55"/>
			<el-table-column fixed prop="id" label="ID"/>
			<el-table-column prop="name" label="名字"/>
			<el-table-column prop="code" label="编码"/>
			<el-table-column prop="updateTime" label="更新时间"/>
            <el-table-column label="操作" align="center" width="200px" fixed="right" #default="scope">
                <el-button size="small" type="primary" @click="showUpdateDialog(scope.row)">更新</el-button>
                <el-button size="small" type="danger" @click="deleteById(scope.row.id)">删除</el-button>
                <el-button size="small" type="success" @click="showAssignedPermissionDialog(scope.row)">权限</el-button>
			</el-table-column>
		</el-table>
		<el-pagination
				v-model:current-page="roleQuery.page"
				v-model:page-size="roleQuery.limit"
				:page-sizes="[10, 20, 30, 40]"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
				@change="loadData"
				style="margin-top: 20px; justify-content: flex-end"
		/>
	</el-card>


	<!--添加、编辑弹出框-->
	<el-dialog v-model="dialogFormVisible" :title="title" width="500" :lock-scroll="false">
		<el-form :model="role">
			<el-form-item label="名字" :label-width="60">
				<el-input v-model="role.name" autocomplete="off"/>
			</el-form-item>
			<el-form-item label="编码" :label-width="60">
				<el-input v-model="role.code" autocomplete="off"/>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取消</el-button>
				<el-button type="primary" @click="addOrUpdate">
					确认
				</el-button>
			</div>
		</template>
	</el-dialog>

<!--    权限分配的dialog-->
    <el-dialog
        title="分配权限"
        v-model="dialogPermissionVisible"
        width="40%" :lock-scroll="false">
        <el-tree
            :data="treeData"
            ref="treeRef"
            show-checkbox
            node-key="id"
            default-expand-all
            :props="defaultProps">
        </el-tree>
        <template #footer>
            <div class="dialog-footer">
            <el-button type="primary" @click="assignPermission()">保存</el-button>
            <el-button  @click="dialogPermissionVisible = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>

<style>
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>
